//
//  LrcHelper.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/4/10.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit
import Alamofire
/// 歌词助手
class LrcHelper: NSObject {
    private class func downloadLrc(_ urlStr:String,_ callback:@escaping ((_ success:Bool,_ lrc:String)->())) -> Void {
        if urlStr.characters.count == 0 {
            callback(false,"Error: urlStr is null")
        }else {
            Alamofire.request(urlStr).responseData { (data) in
                let dataString = String.init(data: data.value!, encoding: String.Encoding.utf8)
                if dataString?.characters.count != 0 {
                    callback(true,dataString!)
                    LrcHelper.storageLrc(urlStr, dataString!)
                    debugPrint("lrc downloaded !")
                }else {
                    callback(false,"")
                }

            }
        }
    }

    private static func lrcDirectory() -> String {
        return NSHomeDirectory().appending("/Documents/lrc")
    }

    private class func storageLrc(_ urlStr:String,_ dataString:String) {
        do {
            let lrcWebUrl = URL.init(string: urlStr)
            let lrcTargetPath = LrcHelper.lrcDirectory().appending("/"+(lrcWebUrl?.lastPathComponent)!)
            if !FileManager.default.fileExists(atPath: LrcHelper.lrcDirectory()) {
                try FileManager.default.createDirectory(atPath: LrcHelper.lrcDirectory(), withIntermediateDirectories: true, attributes: nil)
            }
            try dataString.write(to: URL.init(fileURLWithPath: lrcTargetPath), atomically: true, encoding: String.Encoding.utf8)


        }catch {
            debugPrint(error.localizedDescription)
        }
    }

    private class func lrc(_ urlStr:String, _ callback:@escaping ((_ success:Bool, _ lrc:String)->())) {
        do {
            let lrcWebUrl = URL.init(string: urlStr)
            if lrcWebUrl == nil {
                return
            }
            let lrc = try String.init(contentsOfFile: LrcHelper.lrcDirectory().appending("/"+(lrcWebUrl?.lastPathComponent)!))
                callback(true,lrc)
            debugPrint("lrc read from native !")

        }catch {
            debugPrint(error)
            LrcHelper.downloadLrc(urlStr, callback)
        }
    }



    open class func lrcItems(_ urlStr:String, _ callback:@escaping ((_ lrcItems:[LrcItem]) -> Void)) -> Void {
        LrcHelper.lrc(urlStr) { (success, LrcStr) in
            if success {
                LrcParser.parse(LrcStr, { (lrcItems) in
                    callback(lrcItems)
                })
            }else {
                callback([])
            }
        }
    }
}

struct LrcItem {
    var time:Double?
    var content:String?
    var useful:Bool?
}

private class LrcParser: NSObject {
    class func parse(_ lrcStr:String, _ callback:((_ lrcItems:[LrcItem])->())) {

        var lrcItems = [LrcItem]()

        let lrcParterns = lrcStr.components(separatedBy: "\n")
        for lrcPartern:String in lrcParterns {
            let lrcPSLs = lrcPartern.components(separatedBy: "]")
            if lrcPSLs.count > 0 {
                if lrcPSLs[0].contains(":") && lrcPSLs[0].contains(".") && lrcPSLs[0].characters.count == 9 {
                    var lrcItem = LrcItem()
                    let timeStr = lrcPSLs[0].replacingOccurrences(of: "[", with: "")
                    let times = timeStr.components(separatedBy: ":")
                    lrcItem.time = Double.init(times[0])!*60+Double.init(times[1])!
                    lrcItem.content = ""
                    if lrcPSLs.count == 2 {
                        lrcItem.content =  lrcPSLs[1]
                        lrcItem.content = lrcItem.content?.replacingOccurrences(of: "\r", with: "")
                        lrcItems.append(lrcItem)
                    }
                }
            }
        }
        callback(lrcItems)
        debugPrint("lrc parse completed !")
    }
}
